package com.zpark.controller;

import com.zpark.service.ex.*;
import com.zpark.util.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**控制器的基类*/
public class BaseController {
    /**操作成功的状态码*/
    public static final int OK = 200;

    /**@ExceptionHandler用于统一处理方法抛出的异常*/
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleException(Throwable e){
        JsonResult<Void> result = new JsonResult<Void>(e);
        if (e instanceof UsernameDuplicateException){
            //instanceof  用于判断 e异常属于哪一种异常然后输出对应的json数据
            result.setState(4000);
        }else if (e instanceof UserNotFoundException){
            result.setState(4001);
        }else if (e instanceof PasswordNotMatchException){
            result.setState(4002);
        }else if (e instanceof AddressCountLimitException) {
            result.setState(4003);
        }else if (e instanceof AddressNotFoundException) {
                result.setState(4004);
        } else if (e instanceof AccessDeniedException) {
                result.setState(4005);
        }else if (e instanceof FindHotProductNotFoundException) {
            result.setState(4006);
        } else if (e instanceof FindAllProductNotFoundException) {
            result.setState(4007);
        }else if (e instanceof CartNotFoundException) {
            result.setState(4008);
        } else if (e instanceof InsertException) {
            result.setState(5000);
        }else if (e instanceof DeleteException) {
                result.setState(5002);
        }
        return result;
    }

    protected final Integer getUidFromSession(HttpSession session) {
        return Integer.valueOf(session.getAttribute("uid").toString());
    }

    protected final String getUsernameFromSession(HttpSession session) {
        return session.getAttribute("username").toString();
    }
}
